package com.cys.markdown.doc.admin.logback;

import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.read.CyclicBufferAppender;
import com.cys.common.util.base.MapUtil;
import com.cys.common.util.spring.SpringUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * 循环输出日志
 *
 * @author :caiyushen
 * @createDate: 2019-01-01
 */
public class ExtCyclicBufferAppender<E> extends CyclicBufferAppender {

    @Override
    protected void append(Object eventObject) {

        if (eventObject instanceof LoggingEvent) {
            ExtLogWebSocketEndPoint point = SpringUtils.getBean("extLogWebSocketEndPoint");
            //是否启用日志自动推送
            if (point.getEnablePush()) {
                Info info = addInfo((LoggingEvent) eventObject);
                point.sendAll(info);
            }
        }

        super.append(eventObject);
    }

    private Info addInfo(LoggingEvent event) {
        Info info = new Info();
        info.setDate(new Date(event.getTimeStamp()));
        info.setLevel(event.getLevel());
        info.setLogger(event.getLoggerName());
        info.setThread(event.getThreadName());
        info.setMessage(event.getFormattedMessage());

        throwableHandler(event.getThrowableProxy(), info);

        info.setUserName(MapUtil.getString(event.getMDCPropertyMap(), "loginUserName"));
        return info;
    }

    /**
     * 异常信息处理
     *
     * @param throwableProxy 异常代理
     * @param info           日志信息对象
     */
    private void throwableHandler(IThrowableProxy throwableProxy, Info info) {

        if (throwableProxy != null) {
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            ((ThrowableProxy) throwableProxy).getThrowable().printStackTrace(printWriter);
            String msg = stringWriter.toString();
            msg = msg.replaceAll("at\\s+", "<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;at ");
            info.setExceptionMessage(msg);
        }
    }
}
